const xlsx = require('node-xlsx');
const fs = require('fs');
const path = require('path');

const sub_path = process.argv[2];
console.log('main.js start!', sub_path);

let list = [
    'Stage',
    'Misc',
    'Prop',
    'Item',
    'Skin',
];

for (var i = 0; i < list.length; i++) {
    let key = list[i];
    let srcFile = path.normalize(`${__dirname}/${sub_path}/${key}.xlsx`);
    let tarFile = path.normalize(`${__dirname}/../Game007Creator/assets/ab_config/Xlsx/${key}.json`);
    console.log('开始导入数据', srcFile, '->', tarFile);

    const workSheetsFromFile = xlsx.parse(srcFile);
    let book = workSheetsFromFile.filter(_ => !_.name.startsWith('__'));

    for (let i = 0; i < book.length; i++) {
        let sheet = book[i];
        let firstRow = sheet.data[0];
        if (firstRow == null) break;
        let keepFlag = firstRow.map(_ => {
            if (typeof (_) == 'string') {
                return !_.startsWith('__');
            }
            return true;
        });
        let data = [];
        for (let j = 0; j < sheet.data.length; j++) {
            let row = sheet.data[j];
            if (row != null && row.length > 0 && typeof (row[0]) == 'string' && row[0].startsWith(`//`)) continue;
            let leanRow = [];
            for (let k = 0; k < row.length; k++) {
                let value = row[k];
                if (typeof (value) == 'string' && value.startsWith(`//`)) break;
                if (keepFlag[k] != null && !keepFlag[k]) {
                } else {
                    leanRow.push(value);
                }
            }
            // sheet.data[j] = leanRow;
            data.push(leanRow);
        }
        sheet.data = data;
    }

    let jsonText = JSON.stringify(book);
    console.log('jsonText', jsonText);

    fs.writeFileSync(tarFile, jsonText);

}

console.log('数据导入完毕!');